using System;
using System.Web.UI.WebControls;
using FAQComponents.Objects;

namespace Adge.UI.WebControls
{
	/// <summary>
	/// Summary description for BidirectionalSortableDataGridPage.
	/// </summary>
	public class BidirectionalSortableDataGridPage : System.Web.UI.Page
	{
		#region Protected Page-Level Properties
		protected string SortExpression
		{
			get
			{
				object o = ViewState["SortExpression"];
				if (o == null)
					return string.Empty;
				else
					return o.ToString();
			}
			set
			{
				ViewState["SortExpression"] = value;
			}
		}

		protected bool SortAscending
		{
			get
			{
				object o = ViewState["SortAscending"];
				if (o == null)
					return true;
				else
					return Convert.ToBoolean(o);
			}
			set
			{
				ViewState["SortAscending"] = value;
			}
		}
		#endregion

		protected void BindData(DataGrid dg, IBidirectionalSorter data)
		{
			// sort the results
			data.Sort(SortExpression, SortAscending);

			// Update the columns in the DataGrid
            DGHelpers.UpdateColumnHeaders(dg, SortExpression, SortAscending);

			dg.DataSource = data;
			dg.DataBind();
		}

		protected void HandleSorting(DataGrid dg, string sortExpr)
		{
			dg.CurrentPageIndex = 0;			// reset the DataGrid back to the first page

			if (SortExpression == sortExpr)	// if clicking on same, sorted column then...
				SortAscending = !SortAscending;		// toggle sort direction
			else
				SortAscending = true;				// reset ascending to true when sorting by a new column

			SortExpression = sortExpr;
		}

		protected void HandlePaging(DataGrid dg, int newPageIndex)
		{
			// disable editing
			dg.EditItemIndex = -1;

			dg.CurrentPageIndex = newPageIndex;
		}
	}
}
